package cn.wangkai.peanut.commons.beanutils;

import java.util.Date;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * //日期类型采用自定义转换
 * ConvertUtils.register(new DateConverter(), java.util.Date.class);
 * //日期类型采用自定义转换
 * ConvertUtils.register(new DateConverter(), java.sql.Date.class);
 * BeanUtils.copyProperties(personnel, personnelForm);
 * @author wangkai
 *
 */
public class DateConverter implements Converter {

	private static final Log log = LogFactory.getLog(DateConverter.class);
	
	public DateConverter() {
	}
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Object convert(Class type, Object value) {
		log.debug("type="+type+"||value="+value);
		Date da = null;
		if(value == null||StringUtils.isBlank(String.valueOf(value))) {
			return null;
		}
		if(value instanceof Date) {

			da = (Date)value;
		}else if(value instanceof Long) {
			Long longValue = (Long) value;
			da = new Date(longValue.longValue());
		}else{
			try {
				da = DateUtils.parseDate(value.toString(), new String[] {"yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm","yyyy-MM-dd"});
			} catch (Exception e) {
				throw new ConversionException(e);
			}
		}
		if(type.isAssignableFrom(java.sql.Date.class)){
			return new java.sql.Date(da.getTime());
		}else if(type.isAssignableFrom(java.sql.Timestamp.class)){
			return new java.sql.Timestamp(da.getTime());
		}else{
			return da;
		}
	}
	
	public static void main(String[] args) {
		System.out.println(java.sql.Date.class.isAssignableFrom(Date.class));
		System.out.println(java.sql.Date.class.isAssignableFrom(java.sql.Date.class));
		System.out.println(Date.class.isAssignableFrom(Date.class));
		System.out.println(java.sql.Timestamp.class.isAssignableFrom(Date.class));
	}

}
